package com.mzj.saas.mservice.sreach.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.mservice.sreach.repository.AppKeywordSreachRepository;
import com.mzj.saas.mservice.sreach.vo.AppKeywordSreachVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppKeywordSreachService {
    private static final Logger log = LoggerFactory.getLogger(AppKeywordSreachService.class);

    @Autowired
    private AppKeywordSreachRepository appKeywordSreachRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public ResultBean<ApiData<AppKeywordSreachVO>> pages(String accessToken,Integer pageNumber,Integer pageSize,AppKeywordSreachVO vo){
        log.info("AppKeywordSreachService  pages  accessToken={},vo={} ",accessToken,vo.toString());

        String SQL=" SELECT ks.* FROM saas_app_keyword_sreach ks  ";

        String count=" SELECT count(1) FROM saas_app_keyword_sreach ks  ";

        //String offsets = " limit ? offset ?";

        StringBuilder where = new StringBuilder("WHERE 1 = 1  ");
        List<Object> args = new ArrayList<>();

        if(vo != null){
            if (StringUtils.isNotBlank(vo.getKeyword())){
                where.append(" AND ks.keyword like ? \n");
                args.add("%"+vo.getKeyword()+"%");
            }

        }

        ApiData<AppKeywordSreachVO> apiData = new ApiData<>();

        Long total = jdbcTemplate.queryForObject(count + where, Long.class, args.toArray());
        if (total == 0) {
            return ResultBean.successfulResult(apiData);
        }

        // 查询分页数据
    /*    where.append(" ORDER BY ").append(" ks.create_time desc ").append(" \n").append(offsets);
        args.add(pageSize);
        args.add(pageNumber * pageSize);*/
        List<AppKeywordSreachVO> data = jdbcTemplate.query(SQL + where, new BeanPropertyRowMapper<>(AppKeywordSreachVO.class), args.toArray());

        apiData.setTotal(total);
        apiData.setData(data);
        return ResultBean.successfulResult(apiData);
    }

}
